<?
require("config.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Shipping Fee Rebuilding ...</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
</head>

<body>
<?
$sql="select id,	no,shipping_carrier,	shipping_region from cus_order ";
$order=myQuery($sql);
for ($m=0;$m<count($order);$m++) {
	$shipping_carrier	=	$order[$m][2];
	$shipping_region	=	$order[$m][3];
	$id	= $order[$m][0];
	$no = $order[$m][1];
	
	$sql = "SELECT 
	t.no,
	t.pro_code,
	p.name,
	t.pro_color,
	t.pro_size,
	t.unit_price,
	t.qty,
	t.id ,p.weight,
	p.brand
	FROM cus_order_sub as t,pro_basic as p WHERE t.no='$no' and t.pro_code=p.code";
	$r=myQuery($sql);
	
	$total_qty = 0;
	$total_price = 0;
	$weight=0;
	$Carrierfee=0;


	for ($i=0;$i<count($r);$i++){
	
		$subtotal = $r[$i][5]*$r[$i][6];
		$total_qty += $r[$i][6];
		$total_price += $subtotal;
		$weight += $r[$i][6]*$r[$i][8];
	}

	if ($shipping_carrier=='Self Take') $Carrierfee=0;
	else {
		if (!$shipping_carrier) $shipping_carrier='Air Mail';
		$sql="select charge,weightto from med_shipping where region='$shipping_region' and carrier='$shipping_carrier' order by weightto desc limit 0,1";
		$r=myQuery($sql);
		$maxcharge	= $r[0][0];
		$maxweight	= $r[0][1];
	
		if ($weight<=$maxweight) { 
			$sql="select charge from med_shipping where region='$shipping_region' and carrier='$shipping_carrier' and $weight >= weightfrom and $weight <= weightto;";
			$r=myQuery($sql);
			$Carrierfee= $r[0][0];
		}
		else {
			if($maxweight==0) {
				$Carrierfee= 0;
				$subweight	= 0;
			}
			else {
				$Carrierfee= floor($weight/$maxweight)*$maxcharge;
				$subweight	= $weight - $maxweight * floor($weight/$maxweight);
			}
			$sql="select charge from med_shipping where region='$shipping_region' and carrier='$shipping_carrier' and $subweight >= weightfrom and $subweight <= weightto;";
			$r=myQuery($sql);
			$Carrierfee	+= $r[0][0];
		}
	}
//	echo $Carrierfee.'A<br>';
	if (strpos(strtoupper($shipping_region),'HONG KONG')===false && $shipping_carrier=='Express') {
			$sql="select value from misc_data where name='express'";
			$r=myQuery($sql);
			$rate=$r[0][0];
//			echo $rate .'R<br>';
			$Carrierfee=round($Carrierfee*(100+$rate)/100,2);
	}
	
   $field = array(
	"subtotal",
	"shipping_carrier",
	"shippingfee"
	);


   $content = array(
	$total_price,
	$shipping_carrier,
	$Carrierfee
	);

   $exp = "id=$id";

   myUpdate('cus_order',$field,$content,$exp);
   
   echo "# $no : ($shipping_region , $shipping_carrier) | Subtotal => $subtotal | Shipping Fee => $Carrierfee <br>";


}

?></body>
</html>
